<template>
  <div
      :style="{
      left: `${position.x}px`,
      top: `${position.y}px`,
    }"
      class="draggable-box"
      @mousedown="startDrag"
  >
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  anchorPoint: {
    type: Object,
    default: () => ({ x: 100, y: 100 })
  },
  maxDistance: {
    type: Number,
    default: 100
  }
})

const position = ref({ ...props.anchorPoint })
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })

const startDrag = (e) => {
  isDragging.value = true
  const rect = e.target.getBoundingClientRect()
  dragOffset.value = {
    x: e.clientX - rect.left,
    y: e.clientY - rect.top
  }
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
}

const handleDrag = (e) => {
  if (!isDragging.value) return

  // 计算新位置
  let newX = e.clientX - dragOffset.value.x
  let newY = e.clientY - dragOffset.value.y

  // 计算与锚点的距离
  const dx = newX - props.anchorPoint.x
  const dy = newY - props.anchorPoint.y
  const distance = Math.sqrt(dx*dx + dy*dy)

  // 限制最大距离
  if (distance > props.maxDistance) {
    const angle = Math.atan2(dy, dx)
    newX = props.anchorPoint.x + Math.cos(angle) * props.maxDistance
    newY = props.anchorPoint.y + Math.sin(angle) * props.maxDistance
  }

  position.value = { x: newX, y: newY }
}

const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}
</script>

<style scoped>
.draggable-box {
  position: fixed;
  cursor: move;
  padding: 1rem;
  background: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
  user-select: none;
  z-index: 9999;
}

.draggable-box:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>